﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using ZilLion.Service.Core.Infrastructure.Base;
using ZilLion.Service.Core.Log;
using ZilLion.Service.ObjectStorage.Domain;
using ZilLion.Service.ObjectStorage.Domain.Reponsitorys.Interfaces;

namespace ZilLion.Service.ObjectStorage.Controllers
{
    /// <summary>
    ///     图片上传下载
    /// </summary>
    [Route("Api/img")]
    public class ImgController : ZilLionControllerBase
    {
        private readonly IHostingEnvironment _hostingEnv;
        private readonly IObjectStorageRespository _mongoGridFsRespository;

        public ImgController(IObjectStorageRespository mongoGridFsRespository, IHostingEnvironment hostingEnvironment)
        {
            _mongoGridFsRespository = mongoGridFsRespository;
            _hostingEnv = hostingEnvironment;
        }

        [HttpPost("upload")]
        public UploadResponse UploadFilesAjax()
        {
            var files = Request.Form.Files;
            var result = new UploadResponse {SavedObjects = new List<SavedObjectDto>()};
            foreach (var file in files)
            {
                if (file == null) continue;
                var filename = ContentDispositionHeaderValue
                    .Parse(file.ContentDisposition)
                    .FileName
                    .Trim('"');
                var filestream = file.OpenReadStream();
                var filebyte = StreamToBytes(filestream);
                var fileid = Guid.NewGuid().ToString("N");
                var extension = Path.GetExtension(filename);
                var savdfilename = $"{fileid}{extension}";
                var savedid = string.Empty;
                try
                {
                    savedid = _mongoGridFsRespository.UploadFileToGridFs(filebyte,
                        savdfilename);
                }
                catch (Exception e)
                {
                    ZilLionLogManager.Instance().Error(e);
                }


                var savedObjectDto = new SavedObjectDto
                {
                    ObjectId = savedid,
                    FileName = savdfilename
                };

                result.SavedObjects.Add(savedObjectDto);
            }
            return result;
        }


        [HttpGet("get/{img}")]
        [ResponseCache(VaryByHeader = "User-Agent", Duration = 30)]
        public FileContentResult GetImg(string img)
        {
            var filename = img.UrlDecode();
            //从图片中读取byte
            var imgByte = _mongoGridFsRespository.GetFileBytes(filename);
            if (imgByte == null)
                return new FileContentResult(new List<byte>().ToArray(), "application/octet-stream");
            var extension = string.Empty;
            try
            {
                extension = Path.GetExtension(img);
            }
            catch (Exception)
            {
                // ignored
            }

            var mimeType = "application/octet-stream";
            if (extension != null)
                switch (extension.Replace(".", string.Empty).ToLower())
                {
                    case "gif":
                        mimeType = "image/gif";
                        break;
                    case "jpg":
                        mimeType = "image/jpeg";
                        break;
                    case "png":
                        mimeType = "image/png";
                        break;
                    default:
                        mimeType = "application/octet-stream";
                        break;
                }

            return new FileContentResult(imgByte, mimeType);
        }

        private byte[] StreamToBytes(Stream stream)
        {
            var bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            // 设置当前流的位置为流的开始
            stream.Seek(0, SeekOrigin.Begin);
            return bytes;
        }
    }
}